import SportCategoryModel, {ISportSkill, SPORT_CATEGORY_TYPE_ENUM} from "../models/SportCategoryModel";

class SportCategoryService {
    /** 创建运动类别 */
    public async createSportCategory(params: ISportSkill) {
        try {
            const sportCategory = await SportCategoryModel.create(params);
            return sportCategory;
        } catch (error) {
            console.error(error);
            throw error;
        }
    }

    /** 查询运动类别列表 */
    public async getSportCategoryList(params: {
        pageSize: number;
        pageIndex: number;
        sportCategoryName?: string;
    }) {
        try {
            const {pageSize, pageIndex, sportCategoryName} = params;
            const filterRules: any = {};
            if (sportCategoryName) {
                filterRules.sportCategoryName = {$regex: new RegExp(sportCategoryName)};
            }
            const total = await SportCategoryModel.find().countDocuments();
            const list = await SportCategoryModel.find()
                .where(filterRules)
                .skip((pageIndex - 1) * pageSize)
                .limit(pageSize)
                .select([
                    "sportCategoryName",
                    "sportCategoryType",
                    "sportCategoryId",
                    "createdAt",
                    "updatedAt",
                ])
                .exec();
            return {
                total,
                pageIndex,
                pageSize,
                list,
            };
        } catch (error) {
            console.error(error);
            throw error;
        }
    }

    /** 更新运动类别 */
    public async updateSportCategory(params: ISportSkill) {
        try {
            const sportCategory = await SportCategoryModel.findOneAndUpdate(
                {sportCategoryId: params.sportCategoryId},
                params,
                {
                    new: true,
                }
            );
            return sportCategory;
        } catch (error) {
            console.error(error);
            throw error;
        }
    }

    /** 删除运动类别 */
    public async deleteSportCategory(sportCategoryId: string) {
        try {
            const sportCategory = await SportCategoryModel.findOneAndDelete({sportCategoryId});
            return sportCategory;
        } catch (error) {
            console.error(error);
            throw error;
        }
    }

    /** 获取运动类别信息 */
    public async getSportCategoryById(id: string) {
        try {
            const sportCategory = await SportCategoryModel.findOne({sportCategoryId: id}).select([
                "sportCategoryName",
                "sportCategoryType",
                "sportCategoryId",
                "createdAt",
                "updatedAt",
            ]);
            return sportCategory;
        } catch (error) {
            console.error(error);
            throw error;
        }
    }
}

export default new SportCategoryService();
